home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Power Programmierung
/
Power-Programmierung (Tewi)(1994).iso
/
magazine
/
pctchnqs
/
1990
/
number5
/
bubbler.cpp
< prev
next >
Wrap
C/C++ Source or Header
|
1990-09-28
|
2KB
|
73 lines
#include<stdlib.h>
#include<stdio.h>
#include<iostream.h>
#include<iomanip.h>
const int ARRAY_SIZE = 100;
void swap(int &x, int &y);
int bubble_sort(int *target_array);
void show_array(int *target_array);
void swap(int &x, int &y)
{
int temp; // Define a local integer variable
temp = x; // Store x's value in temp
x = y; // Copy y's value into x
y = temp; // Copy x's value from temp into y
}
int bubble_sort(int *target_array)
{
int sorted_flag = 1;
int i, pass_flag;
do {
pass_flag = 1;
for (i=0; i < ARRAY_SIZE; i++)
if (target_array[i] > target_array[i+1])
{
swap(target_array[i],target_array[i+1]);
sorted_flag = 0;
pass_flag = 0;
}
} while (pass_flag == 0);
return sorted_flag;
}
void show_array(int *target_array)
{
int i,old_width;
old_width = cout.width(5);
for (i=0; i<100; i++)
{
cout << setw(3) << target_array[i];
if ((i+1) % 20 == 0) cout << '\n';
}
cout << '\n';
cout.width(old_width);
}
void main()
{
int i;
int test_array[ARRAY_SIZE]; // Declare an array of 100 integers
for (i=0; i<100; i++)
test_array[i] = rand() % 100;
cout << "Here's the unsorted array:" << "\n";
show_array(test_array);
if (bubble_sort(test_array))
cout << "That array was already sorted!";
else
cout << "The sort of the array is complete. Here it is: \n";
show_array(test_array);
cout << "\n";
}